package com.jeeplus.modules.common.excel.common.validator.chain.impl;

import com.jeeplus.modules.common.excel.common.validator.abs.AbstractCustomValidator;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;
import com.jeeplus.modules.common.excel.common.validator.chain.AbstractValidatorChain;
import com.jeeplus.modules.common.excel.common.validator.impl.*;
import com.jeeplus.modules.common.excel.common.validator.impl.base.*;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * 实现：校验器责任链
 * @author wang.yishu
 */
public class ValidatorChain extends AbstractValidatorChain {

    //校验器接点
    private AbstractValidator node;
    //指针
    private AbstractValidator pointer;

    private Set<String> set = new HashSet<>();

    public ValidatorChain() {
        /*this.addNode(new NotEmptyValidator());
        this.addNode(new DataSizeValidator());
        this.addNode(new IsNumberValidator());
        this.addNode(new IsDateValidator());
        this.addNode(new IsCardIdValidator());
        this.addNode(new IsMobilePhoneValidator());
        this.addNode(new IsPatternValidator());
        this.addNode(new UniqueValidator());

        this.addNode(new DictValidator());
        this.addNode(new CollegeNameValidator());
        this.addNode(new MajorNameValidator());
        this.addNode(new NoteNameValidator());
        this.addNode(new ResearchNameValidator());
        this.addNode(new ClassNameValidator());
        this.addNode(new IsChangeReasonTypeValidator());*/
    }

    @Override
    public String doValidate(Object entity) {
        Class<?> aClass = entity.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        StringBuilder msg = new StringBuilder();
        for (Field declaredField : declaredFields) {
            this.node.validate(entity, declaredField, msg);
        }
        return msg.toString();
    }
    //添加校验器
    public void addNode(AbstractValidator node) {
        if (node == null) {
            return;
        }
        if (set.contains(node.getClassName())) {
            return;
        }
        if (node instanceof AbstractCustomValidator) {
            if (customValidatorList == null) {
                customValidatorList = new ArrayList<>();
            }
            node.setChain(this);
            customValidatorList.add((AbstractCustomValidator) node);
            return;
        }
        node.setChain(this);
        if (this.node == null) {
            this.node = node;
            this.pointer = this.node;
        }
        this.pointer.setNext(node);
        this.pointer = this.pointer.getNext();
        this.set.add(node.getClassName());
    }

}
